package com.voicechat.firstmet.service;

import android.app.Service;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.ServiceConnection;
import android.graphics.PixelFormat;
import android.os.Binder;
import android.os.Build;
import android.os.IBinder;
import android.support.annotation.Nullable;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.WindowManager;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.voicechat.firstmet.App;
import com.voicechat.firstmet.R;
import com.voicechat.firstmet.activity.InviteVoiceChatActivity;
import com.voicechat.firstmet.imcontrol.BroadcastManager;
import com.voicechat.firstmet.utils.Utils;

/**
 * @ProjectName: FirstMet
 * @Package: com.voicechat.firstmet
 * @ClassName: service
 * @Description: 通话最小化服务
 * @Author: ljp
 * @CreateDate: 2018/9/5 16:24
 * @Version: 1.0
 */
public class FloatVideoWindowService extends Service {
    private WindowManager mWindowManager;
    private WindowManager.LayoutParams wmParams;
    private LayoutInflater inflater;
    private String TAG = "FloatVideoWindowService";
    //constant
    private boolean clickflag;

    //view
    private View mFloatingLayout;    //浮动布局
    private RelativeLayout smallSizePreviewLayout; //容器父布局
    private TextView tvTime;//通话时间
  //  private Runnable timeRunable;
   // private Handler handle = new Handler();
    private long currentSecond = 0;//当前毫秒数
    private String formatHMS;

    @Nullable
    @Override
    public IBinder onBind(Intent intent) {
        return new MyBinder();
    }

    public class MyBinder extends Binder {
        public FloatVideoWindowService getService() {
            return FloatVideoWindowService.this;
        }
    }

    public static FloatVideoWindowService newInstance() {
        FloatVideoWindowService fragment = new FloatVideoWindowService();
        return fragment;
    }

    @Override
    public void onCreate() {
        super.onCreate();
        initWindow();//设置悬浮窗基本参数（位置、宽高等）
        initFloating();//悬浮框点击事件的处理
        BroadcastManager.getInstance(App.getContext()).addAction("time", new BroadcastReceiver() {
            @Override
            public void onReceive(Context context, Intent intent) {
                String string = intent.getStringExtra("String");
                String formatHMS = Utils.getFormatHMS(Long.parseLong(string));
                tvTime.setText(formatHMS);
            }
        });
    }
    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        return super.onStartCommand(intent, flags, startId);
    }

    @Override
    public boolean bindService(Intent service, ServiceConnection conn, int flags) {
        return super.bindService(service, conn, flags);

    }


    @Override
    public void unbindService(ServiceConnection conn) {
        BroadcastManager.getInstance(this).destroy("time");
        super.unbindService(conn);
    }

    public  void removeView(){
        // 移除悬浮窗口
        if (mFloatingLayout != null ) {
            smallSizePreviewLayout.setVisibility(View.GONE);
            mFloatingLayout.setVisibility(View.GONE);
            // 移除悬浮窗口
            mWindowManager.removeView(mFloatingLayout);
        }
    }
    public  void setView(){
        if (mFloatingLayout != null ) {
            smallSizePreviewLayout.setVisibility(View.VISIBLE);
            mFloatingLayout.setVisibility(View.VISIBLE);
        }
    }
    @Override
    public void onDestroy() {
        Log.i(TAG, "onDestroy: -----------");
        // 移除悬浮窗口
        if (mFloatingLayout != null ) {
            smallSizePreviewLayout.setVisibility(View.GONE);
            mFloatingLayout.setVisibility(View.GONE);
            // 移除悬浮窗口
            mWindowManager.removeView(mFloatingLayout);
            formatHMS = "";
        }
      //  timeRunable = null;
        BroadcastManager.getInstance(this).destroy("time");
        super.onDestroy();
    }

    @Override
    public boolean onUnbind(Intent intent) {
        if (mFloatingLayout != null ) {
            smallSizePreviewLayout.setVisibility(View.GONE);
            mFloatingLayout.setVisibility(View.GONE);
            // 移除悬浮窗口
            mWindowManager.removeView(mFloatingLayout);

        }
        return super.onUnbind(intent);
    }

    /**
     * 设置悬浮框基本参数（位置、宽高等）
     */
    private void initWindow() {
        mWindowManager = (WindowManager) getApplicationContext().getSystemService(Context.WINDOW_SERVICE);
        wmParams = getParams();//设置好悬浮窗的参数
        // 悬浮窗默认显示以左上角为起始坐标
        wmParams.gravity = Gravity.LEFT | Gravity.TOP;
        //悬浮窗的开始位置，因为设置的是从左上角开始，所以屏幕左上角是x=0;y=0
        wmParams.x = Utils.getSrecchWidth(App.getContext());
        wmParams.y = Utils.getScreenHeight(App.getContext())/2;
        /*if (Build.VERSION.SDK_INT > 25) {//判断当前sdk版本，
            wmParams.type = WindowManager.LayoutParams.TYPE_APPLICATION_OVERLAY;//7.0以上用这个会报错
        } else {
            wmParams.type = WindowManager.LayoutParams.TYPE_PHONE;
        }*/
        if (Build.VERSION.SDK_INT > Build.VERSION_CODES.N_MR1) {
            wmParams.type = WindowManager.LayoutParams.TYPE_APPLICATION_OVERLAY;
        } else if (Build.VERSION.SDK_INT == Build.VERSION_CODES.N_MR1) {
            wmParams.type = WindowManager.LayoutParams.TYPE_SYSTEM_ALERT;
        } else if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
            wmParams.type = WindowManager.LayoutParams.TYPE_TOAST;
        } else {
            wmParams.type = WindowManager.LayoutParams.TYPE_SYSTEM_ALERT;
        }
        //得到容器，通过这个inflater来获得悬浮窗控件
        inflater = LayoutInflater.from(getApplicationContext());
        // 获取浮动窗口视图所在布局
        mFloatingLayout = inflater.inflate(R.layout.service_layout, null);
        // 添加悬浮窗的视图
        mWindowManager.addView(mFloatingLayout, wmParams);
    }


    private WindowManager.LayoutParams getParams() {
        wmParams = new WindowManager.LayoutParams();
        //设置window type 下面变量2002是在屏幕区域显示，2003则可以显示在状态栏之上
       // wmParams.type = WindowManager.LayoutParams.TYPE_TOAST;

        //wmParams.type = WindowManager.LayoutParams.TYPE_PHONE;
        //设置可以显示在状态栏上
        wmParams.flags = WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE | WindowManager.LayoutParams.FLAG_NOT_TOUCH_MODAL |
                WindowManager.LayoutParams.FLAG_LAYOUT_IN_SCREEN | WindowManager.LayoutParams.FLAG_LAYOUT_INSET_DECOR |
                WindowManager.LayoutParams.FLAG_WATCH_OUTSIDE_TOUCH;
        wmParams.format = PixelFormat.RGBA_8888;
        //设置悬浮窗口长宽数据
        wmParams.width = WindowManager.LayoutParams.WRAP_CONTENT;
        wmParams.height = WindowManager.LayoutParams.WRAP_CONTENT;
        //wmParams.alpha = 0.8f;
        return wmParams;
    }

    @Override
    public void onStart(Intent intent, int startId) {
        Log.i(TAG, "onStart: -------------");
        super.onStart(intent, startId);
    }

    private void initFloating() {
        Log.i(TAG, "initFloating: ---------------");
        smallSizePreviewLayout = mFloatingLayout.findViewById(R.id.small_size_preview);
        tvTime = mFloatingLayout.findViewById(R.id.tv_voice_time);
        mFloatingLayout.setVisibility(View.GONE);
        mFloatingLayout.postDelayed(new Runnable() {
            @Override
            public void run() {
                mFloatingLayout.setVisibility(View.VISIBLE);
                smallSizePreviewLayout.setVisibility(View.VISIBLE);
            }
        },500);
        //监听接听方是否接听了广播

       /* timeRunable = new Runnable() {
            @Override
            public void run() {
                    //递归调用本runable对象，实现每隔一秒一次执行任务
                formatHMS = Utils.getFormatHMS(InviteVoiceChatActivity.getCurrentSecond());
               // Log.i(TAG, "run: -------formatHMS--"+formatHMS);
                tvTime.setText(formatHMS);
                handle.postDelayed(this, 1000);
            }
        };
        handle.postDelayed(timeRunable, 0);*/

        //悬浮框点击事件
        smallSizePreviewLayout.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //在这里实现点击重新回到Activity
                //mFloatingLayout.setVisibility(View.GONE);
                Intent start = new Intent(getApplicationContext(),InviteVoiceChatActivity.class);
                start.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK );//| Intent.FLAG_ACTIVITY_REORDER_TO_FRONT
                startActivity(start);
                stopSelf();
            }
        });
        //悬浮框触摸事件，设置悬浮框可拖动
        smallSizePreviewLayout.setOnTouchListener(new FloatingListener());
    }
    //开始触控的坐标，移动时的坐标（相对于屏幕左上角的坐标）
    private int mTouchStartX, mTouchStartY, mTouchCurrentX, mTouchCurrentY;
    //开始时的坐标和结束时的坐标（相对于自身控件的坐标）
    private int mStartX, mStartY, mStopX, mStopY;
 //判断悬浮窗口是否移动，这里做个标记，防止移动后松手触发了点击事件
    private boolean isMove;

    private class FloatingListener implements View.OnTouchListener {

        @Override
        public boolean onTouch(View v, MotionEvent event) {
            int action = event.getAction();
            switch (action) {
                case MotionEvent.ACTION_DOWN:
                    isMove = false;
                    mTouchStartX = (int) event.getRawX();
                    mTouchStartY = (int) event.getRawY();
                    mStartX = (int) event.getX();
                    mStartY = (int) event.getY();
                    break;
                case MotionEvent.ACTION_MOVE:
                    mTouchCurrentX = (int) event.getRawX();
                    mTouchCurrentY = (int) event.getRawY();
                    wmParams.x += mTouchCurrentX - mTouchStartX;
                    wmParams.y += mTouchCurrentY - mTouchStartY;
                    mWindowManager.updateViewLayout(mFloatingLayout, wmParams);

                    mTouchStartX = mTouchCurrentX;
                    mTouchStartY = mTouchCurrentY;
                    break;
                case MotionEvent.ACTION_UP:
                    mStopX = (int) event.getX();
                    mStopY = (int) event.getY();
                    if (Math.abs(mStartX - mStopX) >= 1 || Math.abs(mStartY - mStopY) >= 1) {
                        isMove = true;
                    }
                    break;
            }

            //如果是移动事件不触发OnClick事件，防止移动的时候一放手形成点击事件
            return isMove;
        }
    }


    public interface UpdatePb {
        void update(long progress);
    }
}